package com.gk.util.net
{
		import com.gk.app.SYS;
		
		import flash.events.Event;
		import flash.events.IOErrorEvent;
		import flash.events.TimerEvent;
		import flash.net.URLLoader;
		import flash.net.URLRequest;
		import flash.net.URLRequestMethod;
		import flash.utils.Timer;
		/**
		 *远程数据传输类
		 * 
		 * <br/>以JSON格式向后台请求，并处理响应 
		 * @author Nestor
		 * 
		 */		
		public class RemoteExecuter
		{
			private var dataModelCallBack:Function;
			private var errFunc:Function;
			private var loader:URLLoader;
			private var lastTimer:Timer;
			/**
			 * 
			 * @param params 请求参数
			 * @param serverUrl 请求地址
			 * @param okFun 远程响应回调
			 * @param errFunc 错误处理
			 * @param overTime 超时 ms  默认20000
			 * 
			 */			
			public function RemoteExecuter(params:Object,okFun:Function,errFunc:Function = null,overTime:int = 0)
			{
//				var serverUrl:String ="http://192.168.1.112:8080/gameking/gameking.do";
				this.dataModelCallBack = okFun;
				this.errFunc = errFunc;
				var req:URLRequest = new URLRequest(SYS.serverURL);
				req.contentType = "application/json";
				req.data = JSON.stringify(params);
				req.method = URLRequestMethod.POST;
				loader = new URLLoader();
				loader.addEventListener(Event.COMPLETE, remoteResult);
				loader.addEventListener(IOErrorEvent.IO_ERROR,errStatus);
				loader.load(req);
				var outTime:int = overTime == 0?SYS.overTime:overTime;
				this.lastTimer = new Timer(outTime);
				this.lastTimer.addEventListener(TimerEvent.TIMER,getTimer);
				this.lastTimer.start();
				trace("-------------------------------------------------");
				trace("前端请求：",req.data);
			}
			private function getTimer(e:TimerEvent):void
			{
				trace("超时");
				this.errStatus(null);	
			}
			
			private function remoteResult(e:Event): void
			{
				trace("后台响应：",e.target.data);
				var obj:Object = JSON.parse(String(e.target.data));
				
				if(obj.hasOwnProperty("error")){
					trace("Error!   ","error:",obj.error);
				}else{
					this.dataModelCallBack(obj);
				}
				
				this.dataModelCallBack = this.errFunc = null;
				clear();
			}
			
			private function errStatus(result: IOErrorEvent):void 
			{	
				trace("请求出错：",result.text);
				if(this.errFunc != null)
				{				
					this.errFunc(result);
					this.errFunc = null;
				}
				clear();
			}	
			
			private function clear():void{
				this.lastTimer.stop();
				this.lastTimer.removeEventListener(TimerEvent.TIMER,getTimer);
				this.lastTimer = null;
				loader.removeEventListener(Event.COMPLETE, remoteResult);
				loader.removeEventListener(IOErrorEvent.IO_ERROR,errStatus);
			}
		}
	}